package com.niiwoo.civet.user.service.local;

import com.niiwoo.civet.user.dao.entity.UserExtInfo;
import com.niiwoo.civet.user.dao.mapper.UserExtInfoMapperExt;
import com.niiwoo.civet.user.dto.response.ThirdAuthResponseDTO;
import com.niiwoo.civet.user.dto.response.UserRealNameInfoDTO;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import com.niiwoo.tripod.tiancheng.component.TianchengAuthService;
import com.niiwoo.tripod.tiancheng.component.TianchengAuthZhiMaService;
import com.niiwoo.tripod.tiancheng.request.auth.ThirdAuthRequest;
import com.niiwoo.tripod.tiancheng.request.auth.ZhiMaAuthRequest;
import com.niiwoo.tripod.tiancheng.response.auth.ThirdAuthResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserAuthCommonService {

    @Autowired
    private UserDataService userDataService;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    PrivacyMasks privacyMasks;

    @Autowired
    private UserExtInfoMapperExt userExtInfoMapper;

    public ThirdAuthResponseDTO getThirdAuthUrl(String userId, String createIp, TianchengAuthService tianchengAuthService, String notifyUrl, String callbackUrl, String h5NotifyUrl, boolean isSocialAuth, String locationCity) {
        UserRealNameInfoDTO userRealNameInfoDTO = userDataService.getUserRealNameInfo(userId);
        ThirdAuthRequest request = new ThirdAuthRequest();
        if (userRealNameInfoDTO == null) {
            log.info("调用天秤h5查询用户实名信息为空,userId:" + userId);
            throw new BizException("USR19076");
        }
        if (StringUtils.isBlank(userRealNameInfoDTO.getRealName())
                || StringUtils.isBlank(userRealNameInfoDTO.getIdCard())) {
            log.info("调用天秤h5查询用户真实姓名或身份证号为空,userId:" + userId);
            throw new BizException("USR19076");
        }
        request.setRealName(userRealNameInfoDTO.getRealName());
        request.setMobilePhone(privacyMasks.decryptPrivacy(userRealNameInfoDTO.getMobileNo()));
        request.setIdentityCard(privacyMasks.decryptPrivacy(userRealNameInfoDTO.getIdCard()));
        request.setUserId(userId);
        request.setTransDate(new Date());
        request.setCreateIp(createIp);

        request.setNotifyUrl(notifyUrl);
        request.setCallbackUrl(callbackUrl);
        request.setH5NotifyUrl(h5NotifyUrl);

        //社保授权添加城市参数
        if(isSocialAuth) {
            if(StringUtils.isNotBlank(locationCity)){
                request.setLocationCity(removeEnd(locationCity));
            }else {
                try {
                    UserExtInfo userExtInfo = userExtInfoMapper.selectByPrimaryKey(userId);
                    if (userExtInfo != null) {
                        if (StringUtils.isNotBlank(userExtInfo.getLastLoginCity())) {
                            //天秤的社保地址没有市，去掉市，如：深圳市，变成深圳
                            String city = userExtInfo.getLastLoginCity();
                            city = removeEnd(city);
                            request.setLocationCity(city);
                        }
                    }
                } catch (Throwable e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));

        CompletableFuture<ThirdAuthResponse> future = tianchengAuthService.buildAuthUrl(request);
        try {
            ThirdAuthResponseDTO responseDTO = new ThirdAuthResponseDTO();
            int timeout = 5;
            ThirdAuthResponse response = future.get(timeout, TimeUnit.SECONDS);
            responseDTO.setStatus(response.getStatus());
            responseDTO.setUrl(response.getTch5_url());
            log.info("userId=" + userId + "调用天秤h5Auth返回结果：" + response);
            return responseDTO;
        } catch (Throwable e) {
            log.error("userId=" + userId + "调用天秤h5Auth异常：" + e.getMessage(), e);
        }
        throw new BizException("USR19077");
    }

    /**
     * 去除城市的市
     * @param city
     * @return
     */
    private String removeEnd(String city){
        if (city.length() >= 3 && "市".equals(city.substring(city.length() - 1, city.length()))) {
            return city.substring(0, city.length() - 1);
        }
        return city;
    }

    public ThirdAuthResponseDTO getThirdAuthUrl(String userId, String createIp, TianchengAuthZhiMaService tianchengAuthService, String notifyUrl, String callbackUrl) {
        UserRealNameInfoDTO userRealNameInfoDTO = userDataService.getUserRealNameInfo(userId);
        ZhiMaAuthRequest request = new ZhiMaAuthRequest();
        if (userRealNameInfoDTO == null) {
            log.info("调用天秤h5查询用户实名信息为空,userId:" + userId);
            throw new BizException("USR19076");
        }
        if (StringUtils.isBlank(userRealNameInfoDTO.getRealName())
                || StringUtils.isBlank(userRealNameInfoDTO.getIdCard())) {
            log.info("调用天秤h5查询用户真实姓名或身份证号为空,userId:" + userId);
            throw new BizException("USR19076");
        }
        request.setRealName(userRealNameInfoDTO.getRealName());
        request.setUserId(userId);
        request.setIdentityCard(privacyMasks.decryptPrivacy(userRealNameInfoDTO.getIdCard()));
        request.setTransDate(new Date());
        request.setNotifyUrl(notifyUrl);

        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));

        CompletableFuture<ThirdAuthResponse> future = tianchengAuthService.buildAuthUrl(request);

        try {
            ThirdAuthResponseDTO responseDTO = new ThirdAuthResponseDTO();
            int timeout = 5;
            ThirdAuthResponse response = future.get(timeout, TimeUnit.SECONDS);
            responseDTO.setStatus(response.getStatus());
            responseDTO.setUrl(response.getTch5_url());
            log.info("userId=" + userId + "调用天秤h5Auth返回结果：" + response);
            return responseDTO;
        } catch (Throwable e) {
            log.error("userId=" + userId + "调用天秤h5Auth出现异常：" + e.getMessage(), e);
        }

        throw new BizException("USR19077");
    }

}
